<?php
namespace Home\Controller;
use Think\Controller;

define("TOKEN",'123456');
define("APPID",'wx7ad17a00c66be96d');
define("APPSECRET",'1f0b67a95b9942f877cab88325bd6ee4');
class IndexController extends Controller {
    public function index(){
        $this->responseMsg();
    }

	public function valid(){
        ob_clean();
        $echoStr = $_GET["echostr"];
        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

    public function responseMsg(){
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
      	//extract post data
		if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $tyle = $postObj->MsgType;
                $keyword = trim($postObj->Content);
                $time = time();
                $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";  
                if($tyle=="event" && $postObj->Event=="subscribe"){
                    $msgType = "text";
                    $contentStr = "欢迎关注!";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                }           
				if($keyword=="新安"){
              		$msgType = "text";
                    $contentStr = '<a href="https://www.baidu.com/">帅哥点我啊！</a>';
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                	echo $resultStr;
                }

                $articles = M('article')->where(array('keyword'=>$keyword))->select();
                if(!empty($articles)){
                    $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[news]]></MsgType>
                        <ArticleCount>%s</ArticleCount>
                        <Articles>";
                    foreach ($articles as $a) {
                    $textTpl .= "<item>
                        <Title><![CDATA[".$a['title']."]]></Title> 
                        <Description><![CDATA[".$a['description']."]]></Description>
                        <PicUrl><![CDATA[".$a['picurl']."]]></PicUrl>
                        <Url><![CDATA[".$a['url']."]]></Url>
                        </item>";
                    }
                    $textTpl .= "</Articles>
                    </xml>";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, count($articles));
                    echo $resultStr;
                }else{
                    $url = "http://www.xiaodoubi.com/simsimiapi.php?msg=".$keyword;
                    $msgType = "text";
                    $contentStr = http_get($url);
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                }
        }else {
        	echo "";  
        	exit;
        }
    }

    private function getAccessToken(){
        $access_token_from_file = file_get_contents('access_token');
        $access_token_time_from_file = file_get_contents('access_token_time');
        $now = time();
        if ($now - $access_token_time_from_file >7200) {
            $access_token_api="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=".APPSECRET;
            $data =json_decode(http_get($access_token_api));
            $access_token = $data->access_token;
            file_put_contents('access_token', $access_token);
            file_put_contents('access_token_time', time());
            return $access_token;
        }else{
            return $access_token_from_file;
        }
    }
	
    public function createMeun(){
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
        $file = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=".$access_token;
        $data = array(
            'button'=>array(
                array(
                    'name'=>'菜单',
                    'sub_button'=>array(
                        array(
                            'type'=>'view',
                            'name'=>'搜索',
                            'url'=>'http://www.soso.com/',
                        ),
                        array(
                            'type'=>'view',
                            'name'=>'视频',
                            'url'=>'http://v.qq.com/',
                        ),
                        array(
                            'type'=>'click',
                            'name'=>'赞一下我们',
                            'key'=>'V1001_GOOD'
                        )
                    )
                ),
                array(
                    'name'=>'发图',
                    'sub_button'=>array(
                        array(
                            'type'=>'pic_sysphoto',
                            'name'=>'系统拍照',
                            'key'=>'rselfmenu_1_0',
                        ),
                        array(
                            'type'=>'pic_photo_or_album',
                            'name'=>'相册发图',
                            'key'=>'rselfmenu_1_1',
                        ),
                        array(
                            'type'=>'pic_weixin',
                            'name'=>'微信相册',
                            'key'=>'rselfmenu_1_2'
                        )
                    )
                ),
                array(
                    'name'=>'位置',
                    'sub_button'=>array(
                        array(
                            'name'=>'位置',
                            'type'=>'location_select',
                            'key'=>'rselfmenu_2_0'
                        ),
                        array(
                            'type'=>'media_id',
                            'name'=>'图片',
                            'key'=>'MEDIA_ID1',
                        )
                    )
                )

            )
        );
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $con = http_post($url,$data,$file);
        var_dump($con);
    }

	private function checkSignature(){
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}

?> 